<?php

App::uses('Controller', 'Controller');

/**
 * Application Controller
 *
 * Add your application-wide methods in the class below, your controllers
 * will inherit them.
 *
 * @package		app.Controller
 * @link		http://book.cakephp.org/2.0/en/controllers.html#the-app-controller
 */
class AppController extends Controller {
	public $components = array(
		'DebugKit.Toolbar',
        'Auth' => array(
        	'loginAction' => array('admin' => true, 'controller' => 'login', 'action' => 'index'),
            'loginRedirect' => array('admin' => true, 'controller' => 'login', 'action' => 'index'),
        	'logoutRedirect' => array('admin' => false, 'controller' => 'pages','action' => 'home'),
        	'authError' => 'You must be logged in to view this page.',
        	'loginError' => 'Invalid Username or Password entered, please try again.'
        ),
		'Session'
	);
	
	public $helpers = array('Html', 'Form', 'Session');
	
	public $theme = 'Default';
	public function beforeFilter() {
		if ((isset($this -> params['prefix']) && ($this -> params['prefix'] == 'admin'))) {
			$this->theme = 'Admin';
			if ($this->Auth->loggedIn()) {
				$user = $this->Session->read('Auth.User');
				$this->set('user', $user);
			}
		} else {
			
			$this->theme = 'Default';
			$this->Auth->allow();
		}
		
	}
	
	protected function _checkBrowserLanguage(){
        //checking the 1st favorite language of the user's browser 
        $browserLanguage = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
         
        //available languages
        switch ($browserLanguage){
            case "en":
                $this->Session->write('Config.language', 'eng');
                break;
            case "vi":
                $this->Session->write('Config.language', 'vni');
                break;
            default:
                $this->Session->write('Config.language', 'vni');
        }
    } 

	public function isAuthorized($user) {
	    if (empty($this->params['admin'])) {
	        return true;
	    } else if(AuthComponent::user('role') == 'admin'){
	        return true;
	    }
	    return false;
	}
	function getProductCommon(){
		//$this->_checkBrowserLanguage();
		/*$this->Session->read('Config.language');
		$this -> loadModel('Product');
		// Lấy 5 sản phẩm mới 
		$product_new = $this-> Product ->find('all', 
			array('`Product`.`deleted`' => 0,
				'order' => array('`Product`.`id` DESC'), 
				'limit' => 5
				));		
		$this -> set("productNew", $product_new);

		// Lấy 10 sản phẩm được xem nhiều nhất
		$product_view = $this-> Product ->find('all', 
			array('`Product`.`deleted`' => 0,
				'order' => array('`Product`.`viewer` DESC'), 
				'limit' => 9
				));
		$this -> set("productView", $product_view);	

		$this -> getAgesAndManufactory();*/	
	}

	public function getAgesAndManufactory(){
		$this -> loadModel('Age');
		$this -> loadModel('Manufacturer');

		// Lấy các dữ liệu của ages
		$ages = $this -> Age -> find ('all', array('`Age`.`deteled`' => 0));
		$this -> set("ages", $ages);	

		$manufactory = $this -> Manufacturer -> find ('all', array('`Manufacturer`.`deteled`' => 0));
		$this -> set("manufactory", $manufactory);

		// gán giá trị mặc định cho 2 biến public
		// để khi ra ngoài view, thằng này gọi thằng kia không lỗi
		$this->set("age_id",0);
		$this->set("manufactory_id",0);

		$this -> getImagesSlider();
	}

	public function getImagesSlider(){
		$this -> loadModel('Slider');
		// Lấy các dữ liệu của ages
		$sliders = $this -> Slider -> find ('all', array('`Slider`.`deteled`' => 0));
		$this -> set("sliders", $sliders);	
	}

	public function incrementalHash($len = 5){
		  $charset = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
		  $base = strlen($charset);
		  $result = '';
		   $arr = explode(' ', microtime());
		  $now1 = explode(".",$arr[0]);
		  $now = $now1[1];
		  while ($now >= $base){
		    $i = $now % $base;
		    $result = $charset[$i] . $result;
		    $now /= $base;
		  }
		  return substr($result, -$len).$now1[1];
	}
	function vietnamese_permalink ($title, $replacement = '-')
    {
        /* 	Replace with "-"
		*/
        //$replacement = '-';
        $map = array ();
        $quotedReplacement = preg_quote( $replacement, '/' );
        $default = array (

                '/à|á|ạ|ả|ã|â|ầ|ấ|ậ|ẩ|ẫ|ă|ằ|ắ|ặ|ẳ|ẵ|À|Á|Ạ|Ả|Ã|Â|Ầ|Ấ|Ậ|Ẩ|Ẫ|Ă|Ằ|Ắ|Ặ|Ẳ|Ẵ|å/' => 'a',
                '/è|é|ẹ|ẻ|ẽ|ê|ề|ế|ệ|ể|ễ|È|É|Ẹ|Ẻ|Ẽ|Ê|Ề|Ế|Ệ|Ể|Ễ|ë/' => 'e',
                '/ì|í|ị|ỉ|ĩ|Ì|Í|Ị|Ỉ|Ĩ|î/' => 'i',
                '/ò|ó|ọ|ỏ|õ|ô|ồ|ố|ộ|ổ|ỗ|ơ|ờ|ớ|ợ|ở|ỡ|Ò|Ó|Ọ|Ỏ|Õ|Ô|Ồ|Ố|Ộ|Ổ|Ỗ|Ơ|Ờ|Ớ|Ợ|Ở|Ỡ|ø/' => 'o',
                '/ù|ú|ụ|ủ|ũ|ư|ừ|ứ|ự|ử|ữ|Ù|Ú|Ụ|Ủ|Ũ|Ư|Ừ|Ứ|Ự|Ử|Ữ|ů|û/' => 'u',
                '/ỳ|ý|ỵ|ỷ|ỹ|Ỳ|Ý|Ỵ|Ỷ|Ỹ/' => 'y',
                '/đ|Đ/' => 'd',
                '/ç/' => 'c',
                '/ñ/' => 'n',
                '/ä|æ/' => 'ae',
                '/ö/' => 'oe',
                '/ü/' => 'ue',
                '/Ä/' => 'Ae',
                '/Ü/' => 'Ue',
                '/Ö/' => 'Oe',
                '/ß/' => 'ss',
                '/[^\s\p{Ll}\p{Lm}\p{Lo}\p{Lt}\p{Lu}\p{Nd}]/mu' => ' ',
                '/\\s+/' => $replacement,
                sprintf( '/^[%s]+|[%s]+$/', $quotedReplacement, $quotedReplacement ) => ''
        );
        //Some URL was encode, decode first
        $title = urldecode( $title );
        $map = array_merge( $map, $default );
        return strtolower( preg_replace( array_keys( $map ), array_values( $map ), $title ) );
    }
	function getShortLink($name){
		$shortName = $this->vietnamese_permalink($name);
		$randomChar = substr($this->incrementalHash(5),5);
		return $shortName."-".$randomChar.".html";
	}
	public function createException($data){
		if(count($data) == 0){
			throw new Exception('Trang không tồn tại');
		}
	}
}
